/**
 *
 */
package ua.at.tsvetkov.samizdat.activities;

import ua.at.tsvetkov.samizdat.adapters.AdtLoadedAuthors;
import ua.at.tsvetkov.samizdat.data.DataLoadedAuthors;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Toast;

/**
 * @author A.Tsvetkov 2011, http://tsvetkov.at.ua, al@ukr.net
 */
public class AcLoadedAuthors extends AcTemplate {

	private DataLoadedAuthors	dataLoadedAuthors;
	private AdtLoadedAuthors	adtLoadedAuthors;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addListView();
		dataLoadedAuthors = new DataLoadedAuthors(this);
		dataLoadedAuthors.load();
		if (dataLoadedAuthors.authorsData.length == 0) {
			Toast.makeText(this, "Загрузок пока нет.", Toast.LENGTH_LONG);
			finish();
		}
		adtLoadedAuthors = new AdtLoadedAuthors(dataLoadedAuthors);
		listView.setAdapter(adtLoadedAuthors);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(AcLoadedAuthors.this, AcLoadedAuthorBooks.class);
				intent.putExtra("author", dataLoadedAuthors.authorsData[position].author);
				startActivity(intent);
			}

		});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long id) {
				deleteAuthor(position, view);
				return false;
			}

		});
	}

	private void deleteAuthor(final int position, final View view) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle(dataLoadedAuthors.authorsData[position].author);
		builder.setPositiveButton("Удалить", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dataLoadedAuthors.deleteAutor(position);
				dataLoadedAuthors.load();
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						adtLoadedAuthors.notifyDataSetChanged();
						
					}
				});
			}

		});
		builder.setNegativeButton("Оставить", null);
		builder.show();
	}

	/*
	 * (non-Javadoc)
	 * @see ua.at.tsvetkov.debug.AcSimpleTrackingActivity#onResume()
	 */
	@Override
	protected void onResume() {
		adtLoadedAuthors.refresh();
		if (adtLoadedAuthors.getCount() == 0)
			finish();
		adtLoadedAuthors.notifyDataSetChanged();
		super.onResume();
	}


}
